/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.demo.ui.snap;

/*
 * Snap.java
 * 一个简单的截图程序,参考了两个不同的截图程序
 */

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;


/**
 * @author Vacoor
 */
public class Snap extends JFrame implements MouseListener, MouseMotionListener {
    private static final int SNAP_KEY = KeyEvent.VK_A;

    private Dimension scrDim;  //屏幕大小
    private Robot robot;
    private BufferedImage scrImg;  //全屏幕截图
    private JPanel snapPanel;       //截图面板
    private Point startPoint;       //起点坐标
    private Point endPoint;         //终点坐标
    private int snapWidth;          //截图宽
    private int snapHeight;
    private Color lineColor = Color.BLUE;  //线条颜色
    private boolean isDraw = false; //是否绘画过
    BufferedImage snapImg;

    public Snap() {
        setFeel();
        init();
    }


    private void init() {
        scrDim = Toolkit.getDefaultToolkit().getScreenSize();
        try {
            robot = new Robot();
        } catch (Exception e) {
            System.out.println("创建Root出错");
        }
        scrImg = robot.createScreenCapture(new Rectangle(scrDim));  //创建一个全屏幕截图
        snapPanel = new JPanel() {
            @Override
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.drawImage(scrImg, 0, 0, this);
            }
        };
        snapPanel.addMouseListener(this);
        snapPanel.addMouseMotionListener(this);

        add(snapPanel);
        setUndecorated(true);
//        setAlwaysOnTop(true);
        setCursor(Cursor.CROSSHAIR_CURSOR);
        setSize(scrDim);
        responseToEscKey();
    }
    //构造方法结束

    @Override
    public void mouseClicked(MouseEvent e) {
        if (e.getButton() == MouseEvent.BUTTON3) {
            System.out.println("exit");
            System.exit(0);
        }
    }

    @Override
    public void mousePressed(MouseEvent e) {
        startPoint = e.getPoint();
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        if (e.getButton() == MouseEvent.BUTTON1) {
            snapImg = scrImg.getSubimage(startPoint.x, startPoint.y, Math.abs(startPoint.x - endPoint.x), Math.abs(endPoint.y - startPoint.y));
            //Graphics g=snapPanel.getGraphics();
            //g.clearRect(0, 0, scrDim.width, scrDim.height);
            //g.drawImage(snapImg, 0, 0, this);
            //this.setSize(snapImg.getWidth(),snapImg.getHeight());
            //popUpFileChooser(snapImg);
            new SnapDialog().setLocation(endPoint.x - 110, endPoint.y + 10);//.setVisible(true);
        }
    }

    @Override
    public void mouseEntered(MouseEvent e) {
    }

    @Override
    public void mouseExited(MouseEvent e) {
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        isDraw = true;
        endPoint = e.getPoint();
        snapWidth = Math.abs(endPoint.x - startPoint.x);
        snapHeight = Math.abs(endPoint.y - startPoint.y);
        Graphics g = snapPanel.getGraphics();
        g.setColor(lineColor);
        g.drawImage(scrImg, 0, 0, this);
        g.drawRect(Math.min(startPoint.x, endPoint.x), Math.min(startPoint.y, endPoint.y), snapWidth, snapHeight);
        g.drawString("区域大小:" + snapWidth + "*" + snapHeight, startPoint.x - 15, startPoint.y - 20);
    }

    @Override
    public void mouseMoved(final MouseEvent e) {
        if (!isDraw) {
            final Graphics g = snapPanel.getGraphics();
            g.drawImage(scrImg, 0, 0, this);
            g.setColor(lineColor);
            String str = String.valueOf(e.getPoint().x) + "," + String.valueOf(e.getPoint().y);
            g.drawString(str + "  按住鼠标左键选择截图区域", e.getPoint().x + 15, e.getPoint().y - 20);
        }

    }

    //响应ESC键退出
    private void responseToEscKey() {
        KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
        manager.addKeyEventPostProcessor(new KeyEventPostProcessor() {
            public boolean postProcessKeyEvent(KeyEvent e) {
                if (KeyEvent.VK_ESCAPE == e.getKeyCode()) {
                    System.exit(1);
                }
                return false;
            }
        });
    }

    public final void setFeel() {
        try {
//            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            System.out.println("MainDialog提示: 设置风格遇到异常:" + e);
        }
    }

    //==================================================================
    private void SnapFileChooser(BufferedImage image) {
        JFileChooser picSaveChooser = new JFileChooser();
        //picSaveChooser.setLocation(null);
        picSaveChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
        picSaveChooser.setSelectedFile(null);
        picSaveChooser.addChoosableFileFilter(new BmpFileFilter());
        picSaveChooser.addChoosableFileFilter(new GifFileFilter());
        picSaveChooser.addChoosableFileFilter(new PngFileFilter());
        picSaveChooser.addChoosableFileFilter(new JpgFileFilter());

        if (picSaveChooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) {
            return;
        }
        File file = picSaveChooser.getSelectedFile();
        String path = file.getAbsolutePath().toLowerCase();
        int posExt = path.lastIndexOf(".");
        String ext = "jpg";
        if (posExt > 0) {
            ext = path.substring(posExt + 1);
        }
        file = new File(path += "." + ext);
        try {
            ImageIO.write(image, ext, file);
        } catch (IOException e1) {
            System.out.println("Error:Snap:183");
        }
        //保存后就退出,仿QQ截图
        System.exit(1);
    }

    //以下四个类是为图片保存时弹出的文件选择框提供保存图片的几种类型
    class JpgFileFilter extends FileFilter {
        @Override
        public boolean accept(File file) {
            return file.getName().toLowerCase().endsWith(".jpg");
        }

        @Override
        public String getDescription() {
            return "jpg(*.jpeg,*.jpg)";
        }

    }

    class BmpFileFilter extends FileFilter {
        @Override
        public boolean accept(File file) {
            return file.getName().toLowerCase().endsWith(".bmp");
        }

        @Override
        public String getDescription() {
            return "bmp(*.bmp)";
        }

    }

    class GifFileFilter extends FileFilter {
        @Override
        public boolean accept(File file) {
            return file.getName().toLowerCase().endsWith(".gif");
        }

        @Override
        public String getDescription() {
            return "gif(*.gif)";
        }

    }

    class PngFileFilter extends FileFilter {
        @Override
        public boolean accept(File file) {
            return file.getName().toLowerCase().endsWith(".png");
        }

        @Override
        public String getDescription() {
            return "png(*.png)";
        }

    }

    //===================================================================
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Snap().setVisible(true);
            }
        });
    }


    //截图完成后的对话框
    private class SnapDialog extends JDialog {
        JToolBar toolBar;
        JButton btnUndo;
        JButton btnSave;
        JButton btnClose;
        JButton btnOk;

        SnapDialog() {
            //super();
//            btnUndo=new JButton(new ImageIcon(getClass().getClassLoader().getResource("images/snap_undo.png")));
//            btnSave=new JButton(new ImageIcon(getClass().getClassLoader().getResource("images/snap_save.png")));
//            btnClose=new JButton(new ImageIcon(getClass().getResource("/images/snap_close.png")));
//            btnOk=new JButton(new ImageIcon(getClass().getResource("/images/snap_ok.png")));
            btnUndo = new JButton("undo");
            btnSave = new JButton("save");
            btnClose = new JButton("disconnect");
            btnOk = new JButton("ok");

            btnUndo.setToolTipText("撤销");
            btnSave.setToolTipText("保存");
            btnClose.setToolTipText("关闭");
            btnOk.setToolTipText("完成");
            toolBar = new JToolBar();
            toolBar.add(btnUndo);
            toolBar.add(btnSave);
            toolBar.addSeparator();
            toolBar.add(btnClose);
            toolBar.addSeparator();
            toolBar.add(btnOk);
            toolBar.setFloatable(false);
            toolBar.setRollover(true);
            this.add(toolBar);
            this.setUndecorated(true);
            //this.setSize(106,25);
            this.pack();
            this.setVisible(true);
            this.setAlwaysOnTop(true);
            this.btnUndo.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    isDraw = false;
                    Graphics g = snapPanel.getGraphics();
                    g.drawImage(scrImg, 0, 0, snapPanel);
                    SnapDialog.this.dispose();
                }
            });

            this.btnSave.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    SnapFileChooser(snapImg);
                    //javax.swing.JOptionPane.showMessageDialog(rootPane, "Save");
                }
            });

            this.btnClose.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    System.exit(0);
                }
            });

            this.btnOk.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(getImageTransferable(snapImg), null);
                    System.exit(0);
                    //javax.swing.JOptionPane.showMessageDialog(rootPane, "Ok");
                }
            });
        }

        /**
         * 判断保存到剪切板的内容是否是图像
         *
         * @param image
         * @return
         */
        private Transferable getImageTransferable(final Image image) {
            Transferable transferable = new Transferable() {
                @Override
                public DataFlavor[] getTransferDataFlavors() {
                    return new DataFlavor[]{DataFlavor.imageFlavor};
                }

                @Override
                public boolean isDataFlavorSupported(DataFlavor flavor) {
                    return DataFlavor.imageFlavor.equals(flavor);
                }

                @Override
                public Object getTransferData(DataFlavor flavor)
                        throws UnsupportedFlavorException, IOException {
                    if (isDataFlavorSupported(flavor)) {
                        return image;
                    } else {
                        throw new UnsupportedFlavorException(flavor);
                    }
                }
            };
            return transferable;
        }

    }
}
